<?php

/**
 * This is the model class for table "housing".
 *
 * The followings are the available columns in table 'housing':
 * @property integer $id
 * @property string $name_en
 * @property string $name_ru
 * @property string $name_uk
 * @property string $name_ja
 * @property string $about_en
 * @property string $about_ru
 * @property string $about_uk
 * @property string $about_ja
 * @property integer $area
 * @property string $location
 * @property string $type
 * @property integer $beds
 * @property integer $bath
 * @property integer $price
 * @property integer $amenities
 * @property integer $latitude
 * @property integer $longitude
 * @property string $create_date
 * @property integer $status
 * @property integer $fetuared
 * @property integer $agent_id
 * @property string $owner
 * @property string $reserved_from
 * @property string $reserved_to
 * @property integer $votes
 * @property integer $rate
 * @property string $image
 * The followings are the available model relations:
 * @property HousingImage[] $housingImages
 */


class Housing extends CActiveRecord
{
	/**
	 * @return string the associated database table name
	 */
    public $image;
    public $images;
	public function tableName()
	{
		return 'housing';
	}


    public function behaviors() {
        return array(
            'imageUploadBehavior' => array(
                'class' => 'ext.ImageUploadBehavior',
                'imagePath' => 'uploads',
                'imageField' => 'image',
            ),
        );
    }


	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
//			array('name_en, name_ru, name_uk, name_ja, about_en, about_ru, about_uk, about_ja, area, location, type, beds, bath, price, amenities, latitude, longitude, create_date, status, fetuared, agent_id, owner, reserved_from, reserved_to, votes, rate', 'required'),
			array('name_en, name_ru, name_uk, name_ja, about_en, about_ru, about_uk, about_ja, area, location, type, beds, bath, price, latitude, longitude, status, fetuared, agent_id, owner,  reserved_to', 'required'),
			array('area, beds, bath, price,  status, fetuared, agent_id, votes, rate', 'numerical', 'integerOnly'=>true),
			array('name_en, name_ru, name_uk,  name_ja, reserved_from, location, type, owner, create_date', 'length', 'max'=>255),
            array('amenities','length','max'=>2550),
//            array('image', 'file', 'types'=>'jpg, gif, png, jpeg', 'maxSize' => 100048576),
            array('image, images', 'file', 'types' => 'jpg, gif, png, jpeg', 'allowEmpty' => true, 'maxSize'=>'1024000'),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('id, name_en, name_ru, name_uk, name_ja, about_en, about_ru, about_uk, about_ja, area, location, type, beds, bath, price,  latitude, longitude, create_date, status, fetuared, agent_id, owner, reserved_from, reserved_to, votes, rate', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'housingImages' => array(self::HAS_MANY, 'HousingImage', 'housing_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'name_en' => Yii::t('main', 'Name En'),
			'name_ru' => Yii::t('main', 'Name Ru'),
			'name_uk' => Yii::t('main', 'Name Ua'),
			'name_ja' => Yii::t('main', 'Name Jp'),
			'about_en' => Yii::t('main', 'About En'),
			'about_ru' => Yii::t('main', 'About Ru'),
			'about_uk' => Yii::t('main', 'About Ua'),
			'about_ja' => Yii::t('main', 'About Jp'),
			'area' => Yii::t('main', 'Area'),
			'location' => Yii::t('main', 'Location'),
			'type' => Yii::t('main', 'Type'),
			'beds' => Yii::t('main', 'Beds'),
			'bath' => Yii::t('main', 'Bath'),
			'price' => Yii::t('main', 'Price'),
			'amenities' => Yii::t('main', 'Amenities'),
			'latitude' => Yii::t('main', 'Latitude'),
			'longitude' => Yii::t('main', 'Longitude'),
			'create_date' => Yii::t('main', 'Create Date'),
			'status' => Yii::t('main', 'Status'),
			'fetuared' => Yii::t('main', 'Fetuared'),
			'agent_id' => Yii::t('main', 'Agent'),
			'owner' => Yii::t('main', 'Owner'),
			'reserved_from' => Yii::t('main', 'Reserved From'),
			'reserved_to' => Yii::t('main', 'Reserved To'),
			'votes' => Yii::t('main', 'Votes'),
			'rate' => Yii::t('main', 'Rate'),
			'image' => Yii::t('main', 'Image'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('name_en',$this->name_en,true);
		$criteria->compare('name_ru',$this->name_ru,true);
		$criteria->compare('name_uk',$this->name_uk,true);
		$criteria->compare('name_ja',$this->name_ja,true);
		$criteria->compare('about_en',$this->about_en,true);
		$criteria->compare('about_ru',$this->about_ru,true);
		$criteria->compare('about_uk',$this->about_uk,true);
		$criteria->compare('about_ja',$this->about_ja,true);
		$criteria->compare('area',$this->area);
		$criteria->compare('location',$this->location,true);
		$criteria->compare('type',$this->type,true);
		$criteria->compare('beds',$this->beds);
		$criteria->compare('bath',$this->bath);
		$criteria->compare('price',$this->price);
		$criteria->compare('amenities',$this->amenities,true);
		$criteria->compare('latitude',$this->latitude);
		$criteria->compare('longitude',$this->longitude);
		$criteria->compare('create_date',$this->create_date,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('fetuared',$this->fetuared);
		$criteria->compare('agent_id',$this->agent_id);
		$criteria->compare('owner',$this->owner,true);
		$criteria->compare('reserved_from',$this->reserved_from,true);
		$criteria->compare('reserved_to',$this->reserved_to,true);
		$criteria->compare('votes',$this->votes);
		$criteria->compare('rate',$this->rate);
		$criteria->compare('image',$this->image);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}



    protected function beforeSave(){
        if(isset($_FILES['Housing']['name']['image'])&&$_FILES['Housing']['name']['image']!=''){
//            print_r();exit();
            $imageName=Housing::Model()->findByPk($this->getPrimaryKey())->image;
            $file = $this->getFolderPath() . '/' . $imageName;
            $file240 = $this->getFolderPath() . '/thumb_240/' . $imageName;
            $file270 = $this->getFolderPath() . '/thumb_270/' . $imageName;
            $file870 = $this->getFolderPath() . '/thumb_870/' . $imageName;
            if (file_exists($file) && !is_dir($file)) {
                unlink($file);
            }
            if (file_exists($file240) && !is_dir($file240)) {
                unlink($file240);
            }
            if (file_exists($file270) && !is_dir($file270)) {
                unlink($file270);
            }
            if (file_exists($file870) && !is_dir($file870)) {
                unlink($file870);
            }
        }
        return parent::beforeSave();
    }

    protected function afterSave() {
        parent::afterSave();

        $images = CUploadedFile::getInstances($this, 'images');
        if (isset($images) && count($images) > 0) {
            foreach($images as $k => $img) {
                $imageName = md5(microtime()) . '.' . $img->getExtensionName();
                if($img->saveAs($this->getFolder().$imageName)) {
                    $advImg = new HousingImage();
                    $advImg->housing_id = $this->getPrimaryKey();
                    $advImg->image = $imageName;
                    $advImg->save();

                    Yii::app()->ih
                        ->load($this->getFolder().$imageName)
//                        ->thumb(240, 177)
                        ->adaptiveThumb(240, 177)
                        ->save($this->getFolder() . '/thumb_240/' . $imageName);
                    Yii::app()->ih
                        ->load($this->getFolder().$imageName)
//                        ->thumb(270, 200)
                        ->adaptiveThumb(270, 200)
                        ->save($this->getFolder() . '/thumb_270/' . $imageName);
                    Yii::app()->ih
                        ->load($this->getFolder().$imageName)
//                        ->thumb(870, 420)
                        ->adaptiveThumb(870, 420)
                        ->save($this->getFolder() . '/thumb_870/' . $imageName);
                }
            }
        }
    }

    protected function getFolder() {
        $folder = Yii::getPathOfAlias('webroot') . '/uploads/' . $this->getPrimaryKey() . '/images/';
        if (is_dir($folder) == false)
            mkdir($folder, 0755, true);
        if (is_dir($folder.'thumb_240') == false)
            mkdir($folder.'thumb_240', 0755, true);
        if (is_dir($folder.'thumb_270') == false)
            mkdir($folder.'thumb_270', 0755, true);
        if (is_dir($folder.'thumb_870') == false)
            mkdir($folder.'thumb_870', 0755, true);
        return $folder;
    }

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return Housing the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

    public static function getProp($id=null,$limit=6,$where='')
    {
        $data=($id==null)?$similar = Housing::model()->findAll(
            array(
                "condition" => "$where",
                "order" => "rate",
                "limit" => $limit,
                "together" => true
            )
        ):Housing::Model()->findByPk($id);
        return $data;
    }



    public function searchFilter($posts='5',$filter_location='',$filter_sublocation='',$filter_district='',$filter_type='',
                                        $filter_bedrooms='',$filter_bathrooms='',$filter_price_from='',$filter_price_to='',
                                        $filter_sort_by='',$filter_order='')
    {
        $filter=array();
        (!empty($filter_location))?$filter[]='location="'.mysql_real_escape_string($filter_location).'"':'';
//        $filter[]=(!empty($filter_sublocation))?'sublocation='.$filter_sublocation:'';
//        $filter[]=(!empty($filter_district))?'district='.$filter_district:'';
        (!empty($filter_type))?$filter[]='type="'.mysql_real_escape_string($filter_type).'"':'';
        (!empty($filter_bedrooms))?$filter[]='beds="'.mysql_real_escape_string($filter_bedrooms).'"':'';
        (!empty($filter_bathrooms))?$filter[]='bath="'.mysql_real_escape_string($filter_bathrooms).'"':'';
        (!empty($filter_price_from))?$filter[]='price>"'.mysql_real_escape_string($filter_price_from).'"':'';
        (!empty($filter_price_to))?$filter[]='price<"'.mysql_real_escape_string($filter_price_to).'"':'';
        $order=(isset($filter_order)&&!empty($filter_order)||$filter_order==='DESC')?'DESC':'ASC';
        $sort=(isset($filter_sort_by)&&!empty($filter_sort_by)&&($filter_sort_by=='id'||$filter_sort_by=='name_en'||$filter_sort_by=='name_ru'
                ||$filter_sort_by=='name_ja'||$filter_sort_by=='name_uk'||$filter_sort_by=='area'||$filter_sort_by=='location'
                ||$filter_sort_by=='type'||$filter_sort_by=='price'||$filter_sort_by=='create_date'||$filter_sort_by=='beds'
                ||$filter_sort_by=='bath'))?mysql_real_escape_string($filter_sort_by):'rate';

        $Criteria = new CDbCriteria(array(
            "order" => "$sort $order",
            "together" => true,
        ));
        foreach ($filter as $condition){
            $Criteria->addCondition($condition);
        }
        $pages=new CPagination(Housing::model()->count($Criteria));
        $pages->pageSize=$posts;
        $pages->applyLimit($Criteria);
        $data['pages']=$pages;

        $data['models'] = Housing::model()->findAll($Criteria);
        return $data;
    }
}
